package com.cino.pet.service.impl;

import com.cino.basic.base.mapper.BaseMapper;
import com.cino.basic.base.service.impl.BaseServiceImpl;
import com.cino.pet.domain.PetType;
import com.cino.pet.service.PetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements PetTypeService {
    @Autowired
    private BaseMapper<PetType> baseMapper;

    @Override
    public List<PetType> petTree() {
        //获取所有的petType对象
        HashMap<Long, PetType> hashMap = new HashMap<>();
        List<PetType> petTypes = baseMapper.loadAll();
        for (PetType petType : petTypes) {
            hashMap.put(petType.getId(), petType);
        }
        //前端需要得到的集合数据 - 部门树
        List<PetType> petTypeTree = new ArrayList<>();

        for (PetType petType : petTypes) {
            if (petType.getParentId() == null) {
                petTypeTree.add(petType);
            } else {//不是顶级部门
                //1.想办法找到当前部门的 父部门
                Long parent_id = petType.getParentId();
                //这种从数据库查询的方式，每次通过id去查询 -
                // 查询出来映射给实体domain，children集合中都会是空集合 - 没有任何数据
                PetType parentPetType = hashMap.get(parent_id);

                parentPetType.getChildren().add(petType);
                //常见问题：报空指针异常，原因：上级部门被删除
            }
        }
        return petTypeTree;
    }
}
